import {
  _decorator,
  Collider2D,
  Component,
  Contact2DType,
  Label,
  Node,
  tween,
  Vec3,
} from "cc";
import { GameManager } from "./GameManager";
const { ccclass, property } = _decorator;

@ccclass("Pin")
export class Pin extends Component {
  protected onLoad(): void {
    const collider = this.getComponent(Collider2D);
    if (collider) {
      collider.on(Contact2DType.BEGIN_CONTACT, this.onEndContact, this);
    }
  }

  protected start() {}

  protected update(deltaTime: number) {}

  protected onDestroy(): void {
    const collider = this.getComponent(Collider2D);
    if (collider) {
      collider.off(Contact2DType.BEGIN_CONTACT, this.onEndContact, this);
    }
  }

  public onEndContact(self: Collider2D, otherCollider: Collider2D) {
    GameManager.getInstance().gameOver();

    console.log("发生碰撞", otherCollider.node.name);
  }

  moveTo(targetPos: Vec3, duration: number, parentNode: Node) {
    tween(this.node)
      .to(duration, { position: targetPos }, { easing: "smooth" })
      .call(() => {
        if (parentNode) {
          const p = this.node.getWorldPosition();
          const rotation = this.node.getWorldRotation();
          parentNode.addChild(this.node);
          this.node.setWorldPosition(p);
          this.node.setWorldRotation(rotation);
          if (!GameManager.getInstance().isGameOver) {
            GameManager.getInstance().updateScore();
          }
        }
      })
      .start();
  }
}
